import { useSyncExternalStore } from "react";

let todoList = ['todo #1'];
let listeners = [];

function getTodoList() {
  return todoList;
}

function subscribe(listener) {
  listeners.push(listener);
  return () => {
    listeners = listeners.filter(l => l !== listener)
  };
}

function addTodoList() {
  // * 因为 react 内部通过 Object.is 对比，只是 push 的话，数组本身并没变
  // todoList.push(`todo #${todoList.length + 1}`);
  todoList = [...todoList, `todo #${todoList.length + 1}`];
  listeners.forEach(l => l());
}

export default function App() {
  const _todoList = useSyncExternalStore(subscribe, getTodoList);

  return (
    <div>
      <button onClick={addTodoList}>+1</button>
      <ul>
        {_todoList.map(todo => <li key={todo}>{todo}</li>)}
      </ul>
    </div>
  );
}
